import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  // baseURL: 'https://api-hmzs.itheima.net/v1',
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    // console.log(token)

    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      // `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data instanceof Blob) {
      return response.data
    }

    if (response.data.code !== 10000) {
      Message.error(response.data.msg)
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  },
  error => {
    Message.error(error.response.data.error ? error.response.data.error : error.response.data.msg)
    // console.log(error.response)

    // token 401处理
    if (error.response.status === 401) {
      // 跳转到登录
      store.commit('user/removeToken')
      router.replace('/login')
    }
    return Promise.reject(error)
  }
)

export default service
